;(function() {

	define(['jquery', 'angular', 'uiBootstrap', 'cookies'], function($, angular) {

		var app = angular.module('app', ['ui.bootstrap', 'ngCookies']), norms = '',
		islogin = $('.header .link-area').attr('isguest') == 'false' ?
					true : false,
		pathname = window.location.pathname;

		app.factory('safeApply', ['$rootScope', function($rootScope) {//apply
		    return function(scope, fn) {
		        var phase = scope.$root.$$phase;
		        if (phase == '$apply' || phase == '$digest') {
		            if (fn && ( typeof (fn) === 'function')) fn();
		        } else {
		            scope.$apply(fn);
		        }
		    }
		}])

		.controller('storeGoods', ['$scope', '$timeout', 'safeApply', '$http', '$cookieStore', function($scope, $timeout, safeApply, $http, $cookieStore) {

			$scope.loading = false;//loading开关

			$scope.norms = {
				clientId: $('.c-header').attr('init'),
				id: $('.goods .inner .info').attr('pdtid'),
				selTips: true,//采购清单为空提示
				price: JSON.parse($('.right .top .price .row').eq(1).attr('data')),//价格区间
				isMix: $('.goods .info').attr('ismix')=='Y'?1:0,//是否混批,1是0不是
				totNum: 0,//总计数量
				totPrice: 0,//总价
				color: $('.sku-list.color').attr('data') ? 
						$('.sku-list.color').attr('data').split('|') :
						'',
				size: $('.sku-list.size').attr('data') ? 
						$('.sku-list.size').attr('data').split('|') : '',
				canSize: $('.sku-list.color').attr('selectdata') ? 
							$('.sku-list.color').attr('selectdata').split(',') : '',//存在的组合
				SKUtot: {},//规格选择集合
				sizeRow: {},
				sizeRowLen: 0,
				stock: $('.goods .inner .info').attr('stock'),
				type: $('.goods .inner .info').attr('type')=='2'?1:0,//1是现货2是期货
			}

			$scope.norms.sizeRowLen = $scope.norms.size.length;

			$scope.tab3 = {//tab-3页
				pageNum: 10,//默认1页,这里数字需要X10
				currentPage: 1,//当前页数
				maxSize: 5,//分页个数
				hits: 25,//每个分页显示列表数量
				isLoad: false//是否已加载
			};

			norms = $scope.norms;

			$timeout(function() {

				$('.sku-list.color .list a').eq(0).click();
			}, 10);

			for(var a=0;a<norms.color.length;a++) {//创建每个size对象

				norms.SKUtot[norms.color[a]] = {
					totNum: 0,//总数量
					size: {},
				};
				for(var b=0;b<norms.size.length;b++) {
					norms.SKUtot[norms.color[a]].size[norms.size[b]] = {
						qty: 0,
						num: '0',
						uPrice: norms.price[0].price,
						dis: norms.canSize.indexOf(norms.color[a] + '|' + norms.size[b]) >-1 ?
								false : true
					}
				}
			}

			$scope.changeList = function(color, el) {

				if(norms.type == 1) {
					$http({
						method: 'POST',
						url: '/control/pub/command',
						params: {
							'command': "com.jackrain.ds.CommESGoodsStorageQuerypub",
							'SPEC1': color,
							'ES_GOODS_ID': norms.id,
							'getjson': true,
						}
					}).then(function(res) {
						
						if(res.data.code == 0)
							 for(var i=0;i<res.data.spdata.length;i++) {
							 	norms.SKUtot[color].size[res.data.spdata[i].SPEC2].qty = res.data.spdata[i].QTY;
							 }
					}, function(res) {

						if(!res.data) {

							alert('获取库存失败,请稍候重试');
							return false;
						}
					});
				} else {

					for(var i in norms.SKUtot[color].size) {
					 	norms.SKUtot[color].size[i].qty = norms.stock;
					}
				}

				for(var i in norms.sizeRow) {
					norms.sizeRow[i].size = norms.SKUtot[color].size[i];
				}

				var array = [];
				for(var i in norms.SKUtot) {//排查存在数量的颜色
					
					if(norms.SKUtot[i].totNum > 0)
						array.push(i);
				}
				
				safeApply($scope);
				return array;
			}

			$scope.count = function() {

				var tprice = 0;
				var tnum = 0;
				for(var i in norms.SKUtot) {//计算数量
					var itot = 0;
					var iprice = 0;

					for(var k in norms.SKUtot[i].size) {

						itot += parseInt(norms.SKUtot[i].size[k].num);
					}

					norms.SKUtot[i].totNum = itot;
					tnum += itot;
					if(norms.isMix)
						iprice =  
							norms.price[2] && itot > norms.price[2].qty ?//大于第三个价格段
								norms.price[2].price :
							norms.price[1] && itot > norms.price[1].qty ?//大于第二个价格段
								norms.price[1].price : norms.price[0].price;

					for(var k in norms.SKUtot[i].size) {

						if(norms.isMix)
							norms.SKUtot[i].size[k].uPrice = iprice;

						tprice += norms.SKUtot[i].size[k].num * norms.SKUtot[i].size[k].uPrice;
					}
				}

				norms.totNum = tnum;
				norms.totPrice = tprice;
				safeApply($scope);
			}

			$scope.addCart = function() {

				if(!islogin) {

					if(norms.totNum > 0)
						$cookieStore.put('addCart',norms.SKUtot);

					var login = new jBox('Modal', {					    
					    title: '用户登录',
					    closeOnClick: 'body',
					    closeButton: 'title',
					    ajax: {
						    url: '/esvml/login/login.htm?redirect=' + pathname + '?getCart=' + pathname.replace(/\/j\/s\/pdt\/|\.html/gi, ''),
						    reload: false,
						    setContent: true,
						    spinner: true
						},
					    onCloseComplete: function() {
					    	login.destroy();
					    }
					}).open();
				} else if(norms.totNum <= 0) {

					new jBox('Notice', {
						autoClose: 3000,
						addClass: 'font-b',
						content: '订购数量必须为大于0',
						position: {
							x: 'center',
							y: 50
						}
					});
					return false;
				} else {

					var _params = [{
						'ad_client': norms.clientId,
						'items': []
					}]

					for(var a in norms.SKUtot) {

						for(var b in norms.SKUtot[a].size) {
							if(parseInt(norms.SKUtot[a].size[b].num) > 0)
								_params[0]['items'].push({
									"qty": parseInt(norms.SKUtot[a].size[b].num),
							      	"price": norms.SKUtot[a].size[b].uPrice,
							      	"totprice": norms.SKUtot[a].size[b].num * norms.SKUtot[a].size[b].uPrice,
							      	"specvalue": [a, b].join('|'),
							      	"spec1": a,
							      	"spec2": b,
							      	'goodsid': norms.id,
							  	});
						}
					}

					$http({
						method: 'POST',
						url: '/control/command',
						params: {
							'command': 'com.jackrain.ds.CommESShopCartSave',
							'getjson': true,
							'JSON': JSON.stringify(_params)
						}
					}).then(function(res) {

						if(res.data.code == 0 && res.data.message == '操作完成') {

							new jBox('Notice', {
								autoClose: 3000,
								addClass: 'font-b',
								content: '添加成功',
								position: {
									x: 'center',
									y: 50
								}
							});

							for(var a in norms.SKUtot) {
								for(var b in norms.SKUtot[a].size) {
									if(parseInt(norms.SKUtot[a].size[b].num) > 0)
										norms.SKUtot[a].size[b].num = '0';
								}
							}
						} else if(!res.data) {

						}
					});
				}//else
			}//添加购物车

			$scope.goPay = function() {
				if(!islogin) {

					if(norms.totNum > 0)
						$cookieStore.put('addCart',norms.SKUtot);

					var login = new jBox('Modal', {					    
					    title: '用户登录',
					    closeOnClick: 'body',
					    closeButton: 'title',
					    ajax: {
						    url: '/esvml/login/login.htm?redirect=' + pathname + '?getCart=' + pathname.replace(/\/j\/s\/pdt\/|\.html/gi, ''),
						    reload: false,
						    setContent: true,
						    spinner: true
						},
					    onCloseComplete: function() {
					    	login.destroy();
					    }
					}).open();
				} else if(norms.totNum <= 0) {

					new jBox('Notice', {
						autoClose: 3000,
						addClass: 'font-b',
						content: '订购数量必须为大于0',
						position: {
							x: 'center',
							y: 50
						}
					});
					return false;
				} else {
					$http({
						method: 'POST',
						url: '/control/command',
						params: {
							'command': 'com.jackrain.ds.CommESOrderSave',
							'getjson': true,
							'JSON': JSON.stringify(_items)
						}
					}).then(function(res) {

					});
				}
			}

			if(islogin && getUrlOpt('getCart') == pathname.replace(/\/j\/s\/pdt\/|\.html/gi, '') && $cookieStore.get('addCart') && JSON.stringify($cookieStore.get('addCart'))) {
				norms.SKUtot = $cookieStore.get('addCart');
				$cookieStore.remove('addCart');
				$scope.count();
				$scope.addCart();
			}
		}])
		.directive('color', ['safeApply', function(safeApply) {
			return {
				restrict: 'A',
				scope: true,
				link: function(scope, el, attrs) {

					scope.color = attrs.color;
					el.on('click', function(e) {
							
						if($(this).children('button').hasClass('sel')) return false;

						$(this).children('button').addClass('sel');
						$(this).siblings('a').children('button').removeClass('sel');

						var res = scope.$parent.changeList(scope.color, el);

						$('.sku-list.color .list a button').removeClass('active');
						if(res.length > 0) {

							for(var i=0;i<res.length;i++) {

								$('.sku-list.color .list a[color='+ res[i] +'] button').addClass('active');
							}
						}
					});
				}
			}
		}])
		.directive('sizeRow', ['safeApply', function(safeApply) {

			return {
				restrict: 'A',
				scope: true,
				controller: ['$scope', '$element', '$attrs', function($scope, el, attrs) {
					
					$scope.size = {
						num: '0',
						qty: 0,
						uPrice: norms.price[0].price,
						dis: false
					}

					$scope.$watch('size.num', function(val) {

						$scope.size.num = val.replace(/\D|\s/gi,'') != ''?
											parseInt(val.replace(/\D|\s/gi,'')) + '' :
											0 + '';

						if(parseInt($scope.size.num) > $scope.size.qty)
							$scope.size.num = $scope.size.qty + '';

						if(!norms.isMix)

							$scope.size.uPrice =  
								norms.price[2] && (parseInt($scope.size.num) > norms.price[2].qty) ?//大于第三个价格段
									norms.price[2].price :
								norms.price[1] && (parseInt($scope.size.num) > norms.price[1].qty) ?//大于第二个价格段
									norms.price[1].price : norms.price[0].price;

						$scope.$parent.count();
					});

					norms.sizeRow[attrs.sizeRow] = $scope;

					$scope.count = function(opt) {

						if(opt) {

							$scope.size.num = (parseInt($scope.size.num) + 1) <= $scope.size.qty ?
										  (parseInt($scope.size.num) + 1) + '' :
										  $scope.size.qty + '';

						} else {

							$scope.size.num = (parseInt($scope.size.num) - 1) >= 0 ?
										  (parseInt($scope.size.num) - 1) + '' :
										  0 + '';
						}
					}
				}]
			}
		}]);

		angular.element(document).ready(function() {
			angular.bootstrap(document, ['app']);
		});

		function getUrlOpt(name){

		     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
		     var r = window.location.search.substr(1).match(reg);

		     if(r != null) 
		     	return  unescape(r[2]); 
		     return null;
		}
		
		return app;
	});
})();